package com.bugbuff.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.bugbuff.dubbo.server.enums.IdType;
import com.bugbuff.dubbo.server.pojo.Users;
import com.bugbuff.dubbo.server.pojo.Voice;
import com.bugbuff.dubbo.server.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VoiceApiImpl implements VoiceApi {

    //用户获取语音剩余次数数据存储在Redis中key的前缀
    private static final String REMANNING_REDIS_KEY_PREFIX = "REMANNING_TIME_";

    //用户获取过的语音vid对应的key的前缀
    private static final String VOICE_REDIS_KEY_PREFIX = "VOICE_RECEIVED_";

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 保存语音文件
     * @param voice
     * @return
     */
    @Override
    public String saveVoice(Voice voice) {
        try {
            //对数据进行校验
            if(!ObjectUtil.isAllNotEmpty(voice.getUserId(),voice.getVoiceUrl())){
                return null;
            }
            //设置vid键值
            voice.setVid(idService.createId(IdType.VOICE));
            voice.setCreated(System.currentTimeMillis());
            //保存视频
            mongoTemplate.save(voice);
            return voice.getId().toHexString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取语音集合：排除登录用户的好友发送的语音
     * @param userId
     * @return
     */
    @Override
    public List<Voice> queryVoice(Long userId) {
        //查询登录用户的好友
        Query query=Query.query(Criteria.where("userId").is(userId));
        List<Users> usersList = mongoTemplate.find(query, Users.class);
        //获取好友的userid集合
        List<Object> friendIds = CollUtil.getFieldValues(usersList, "friendId");
        //排除自己发出的语音
        friendIds.add(userId);
        //排除redis中用户已经接收过的语音
        List<Long> vidList=new ArrayList<>();
        if(redisTemplate.hasKey(this.getVoiceKey(userId))){
            String vids = redisTemplate.opsForValue().get(this.getVoiceKey(userId));
            String[] vidsArr = StringUtils.split(vids, ",");
            for (String vid : vidsArr) {
                vidList.add(Convert.toLong(vid));
            }
        }
        //查询排除自己和好友的语音
        Query voiceQuery=Query.query(Criteria.where("userId").nin(friendIds));
        if(CollUtil.isNotEmpty(vidList)){
            voiceQuery.addCriteria(Criteria.where("vid").nin(vidList));
        }
        List<Voice> voiceList = mongoTemplate.find(voiceQuery, Voice.class);
        //查询redis中用户获取语音的剩余次数
        String redisKey=this.getRemanningKey(userId);
        String redisData = redisTemplate.opsForValue().get(redisKey);
        if(StringUtils.isEmpty(redisData)){
            //没有数据，说明是第一次接收语音，还剩9次
            redisTemplate.opsForValue().set(redisKey,"9");
        }else{
            //不是第一次获取，次数减1
            redisTemplate.opsForValue().increment(redisKey,-1);
        }

        return voiceList;
    }

    private String getRemanningKey(Long userId) {
        return REMANNING_REDIS_KEY_PREFIX+userId;
    }

    private String getVoiceKey(Long userId) {
        return VOICE_REDIS_KEY_PREFIX+userId;
    }
}
